﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.Xml;

namespace ShareMarking.HondaLottery.Auto
{
    public class AppConfigTools
    {


        /// 配置文件
        /// </summary>
        public enum ConfigurationFile
        {
            /// <summary>
            /// WinForm配置文件
            /// </summary>
            AppConfig = 1,
            /// <summary>
            /// WebForm配置文件
            /// </summary>
            WebConfig = 2
        }

        ///<summary>
        ///在＊.exe.config文件中appSettings配置节增加一对键、值对
        ///</summary>
        ///<param name="newKey"></param>
        ///<param name="newValue"></param>
        public static void UpdateAppConfig(string newKey, string newValue)
        {
            bool isModified = false;
            foreach (string key in ConfigurationManager.AppSettings)
            {
                if (key == newKey)
                {
                    isModified = true;
                    break;
                }
            }
            // Open App.Config of executable
            Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            // You need to remove the old settings object before you can replace it
            if (isModified)
            {
                config.AppSettings.Settings.Remove(newKey);
            }
            // Add an Application Setting.
            config.AppSettings.Settings.Add(newKey, newValue);
            // Save the changes in App.config file.
            config.Save(ConfigurationSaveMode.Modified);
            // Force a reload of a changed section.
            ConfigurationManager.RefreshSection("appSettings");
        }



        ///<summary> 
        ///返回＊.exe.config文件中appSettings配置节的value项  
        ///</summary> 
        ///<param name="strKey"></param> 
        ///<returns></returns> 
        public static string GetAppConfig(string strKey)
        {
            foreach (string key in ConfigurationManager.AppSettings)
            {
                if (key == strKey)
                {
                    return ConfigurationManager.AppSettings[strKey];
                }
            }
            return null;
        }



        ///<summary> 
        ///依据连接串名字connectionName返回数据连接字符串  
        ///</summary> 
        ///<param name="connectionName"></param> 
        ///<returns></returns> 
        public static string GetConnectionStringsConfig(string connectionName)
        {
            string connectionString = ConfigurationManager.ConnectionStrings[connectionName].ConnectionString.ToString();
            return connectionString;
        }


        ///<summary> 
        ///更新连接字符串  
        ///</summary> 
        ///<param name="newName">连接字符串名称</param> 
        ///<param name="newConString">连接字符串内容</param> 
        ///<param name="newProviderName">数据提供程序名称</param> 
        public static bool UpdateConnectionStringsConfig(string newName, string newConString, string newProviderName)
        {
            bool isModified = false;
            //记录该连接串是否已经存在  

            //如果要更改的连接串已经存在     
            if (ConfigurationManager.ConnectionStrings[newName] != null)
            {
                isModified = true;
            }
            //新建一个连接字符串实例      
            ConnectionStringSettings mySettings = new ConnectionStringSettings(newName, newConString, newProviderName);
            // 打开可执行的配置文件*.exe.config      
            Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            // 如果连接串已存在，首先删除它      
            if (isModified)
            {
                config.ConnectionStrings.ConnectionStrings.Remove(newName);
            }
            // 将新的连接串添加到配置文件中.      
            config.ConnectionStrings.ConnectionStrings.Add(mySettings);
            // 保存对配置文件所作的更改      
            config.Save(ConfigurationSaveMode.Modified);

            // 强制重新载入配置文件的ConnectionStrings配置节 
            //更新大小写ConnectionStrings，即时生效
            ConfigurationManager.RefreshSection("ConnectionStrings");
            ConfigurationManager.RefreshSection("connectionStrings");

            return true;
        }


        /// <summary>
        /// 对[connectionStrings]节点依据name值读取到connectionString值，返回字符串
        /// </summary>
        /// <param name="configurationFile">要操作的配置文件名称,枚举常量</param>
        /// <param name="name">要读取的name值</param>
        /// <returns>返回connectionString值的字符串</returns>
        public static string ReadConnectionStringByName(ConfigurationFile configurationFile, string name)
        {
            string connectionString = string.Empty;
            string filename = string.Empty;
            if (configurationFile.ToString() == ConfigurationFile.AppConfig.ToString())
            {
                filename = System.Windows.Forms.Application.ExecutablePath + ".config";
            }
            else
            {
                filename = System.AppDomain.CurrentDomain.BaseDirectory + "web.config";
            }

            XmlDocument doc = new XmlDocument();
            doc.Load(filename); //加载配置文件

            XmlNode node = doc.SelectSingleNode("//connectionStrings");   //得到[appSettings]节点

            ////得到[connectionString]节点中关于name的子节点
            XmlElement element = (XmlElement)node.SelectSingleNode("//add[@name='" + name + "']");

            if (element != null)
            {
                connectionString = element.GetAttribute("connectionString");
            }

            return connectionString;
        }


        /// <summary>
        /// 更新或新增[connectionStrings]节点的子节点值，存在则更新子节点,不存在则新增子节点，返回成功与否布尔值
        /// </summary>
        /// <param name="configurationFile">要操作的配置文件名称,枚举常量</param>
        /// <param name="name">子节点name值</param>
        /// <param name="connectionString">子节点connectionString值</param>
        /// <param name="providerName">子节点providerName值</param>
        /// <returns>返回成功与否布尔值</returns>
        public static bool UpdateOrCreateConnectionString(ConfigurationFile configurationFile, string name, string connectionString, string providerName)
        {
            bool isSuccess = false;
            string filename = string.Empty;
            if (configurationFile.ToString() == ConfigurationFile.AppConfig.ToString())
            {
                filename = System.Windows.Forms.Application.ExecutablePath + ".config";
            }
            else
            {
                filename = System.AppDomain.CurrentDomain.BaseDirectory + "web.config";
            }

            XmlDocument doc = new XmlDocument();
            doc.Load(filename); //加载配置文件

            XmlNode node = doc.SelectSingleNode("//connectionStrings");   //得到[connectionStrings]节点

            try
            {
                ////得到[connectionStrings]节点中关于Name的子节点
                XmlElement element = (XmlElement)node.SelectSingleNode("//add[@name='" + name + "']");

                if (element != null)
                {
                    //存在则更新子节点
                    element.SetAttribute("connectionString", connectionString);
                    element.SetAttribute("providerName", providerName);
                }
                else
                {
                    //不存在则新增子节点
                    XmlElement subElement = doc.CreateElement("add");
                    subElement.SetAttribute("name", name);
                    subElement.SetAttribute("connectionString", connectionString);
                    subElement.SetAttribute("providerName", providerName);
                    node.AppendChild(subElement);
                }

                //保存至配置文件(方式二)
                doc.Save(filename);

                isSuccess = true;
            }
            catch (Exception ex)
            {
                isSuccess = false;
                throw ex;
            }

            return isSuccess;
        }



    }
}
